package com.imooc.controller;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.imooc.Interceptor.JwtCurrentUserInterceptor;
import com.imooc.bo.CreateAdminInfoBO;
import com.imooc.bo.UpdateAdminBO;
import com.imooc.pojo.Admin;
import com.imooc.result.GraceJSONResult;
import com.imooc.service.AdminInfoService;
import com.imooc.utils.PagedGridResult;
import com.imooc.vo.AdminInfoVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

/**
 * 管理端用户Controller
 * @author liansen
 * @create 02-13-11:38
 */
@RestController
@RequestMapping("/admininfo")
public class AdminInfoController {

    @Autowired
    private AdminInfoService adminInfoService;

    //分配账号
    @PostMapping("/create")
    public GraceJSONResult createAdminInfo(@Validated @RequestBody CreateAdminInfoBO adminInfoBO){
        adminInfoService.createAdminInfo(adminInfoBO);
        return GraceJSONResult.ok();
    }

    //条件分页查询
    @PostMapping("/list")
    public GraceJSONResult list(@RequestParam("page") Integer page,
                                @RequestParam("limit") Integer limit,
                                @RequestParam("accountName") String accountName){
        if(page == null){
            page = 1;
        }
        if(limit == null){
            limit = 10;
        }
        PagedGridResult result = adminInfoService.queryPage(page, limit, accountName);
        return GraceJSONResult.ok(result);
    }

    //删除
    @PostMapping("/delete")
    public GraceJSONResult delete(@RequestParam("username") String username){
        if(StringUtils.isBlank(username)){
            return GraceJSONResult.error();
        }
        adminInfoService.deleteAdmin(username);
        return GraceJSONResult.ok();
    }


    @PostMapping("/myInfo")
    public GraceJSONResult myInfo(){
        Admin admin = JwtCurrentUserInterceptor.adminUser.get();
        Admin adminInfo = adminInfoService.getById(admin.getId());
        AdminInfoVO adminInfoVO = new AdminInfoVO();
        BeanUtils.copyProperties(adminInfo, adminInfoVO);
        return GraceJSONResult.ok(adminInfoVO);
    }

    @PostMapping("/updateMyInfo")
    public GraceJSONResult updateMyInfo(@RequestBody UpdateAdminBO updateAdminBO){
        Admin admin = new Admin();
        BeanUtils.copyProperties(updateAdminBO, admin);
        admin.setUpdatedTime(LocalDateTime.now());
        adminInfoService.updateById(admin);
        return GraceJSONResult.ok();
    }

}